<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/15
 * Time: 17:10
 * @link http://www.lmterp.cn
 */
namespace app\common\service\finance;

use app\common\library\Tools;
use app\common\model\FinanceBank;
use app\common\model\FinanceCash;
use app\common\model\FinanceInvoiceSetting;
use app\common\model\FinancePayment;
use app\common\service\BaseService;
use think\Db;
use think\exception\DbException;
use think\facade\Hook;
use think\facade\Log;

/**
 * 财务模块服务类
 * Class FinanceService
 * @package app\common\service\finance
 */
class FinanceService extends BaseService
{
    /**
     * 添加付款单
     * @param array $data 付款信息
     * @return FinancePayment|false
     * @date 2020/12/15
     * @author longli
     */
    public function addPayment($data = [])
    {
        $pData = FinancePayment::getFilterField($data, '');
        if(empty($pData)) return false;
        $pData = Tools::trim($pData);
        $payment = null;
        if(isset($pData['payment_id'])) $payment = FinancePayment::get($pData['payment_id']);
        if(empty($payment) && isset($pData['ref_id_type']) && isset($pData['ref_sn']) && isset($pData['cash_money']))
            $payment = FinanceCash::get(['ref_id_type' => $pData['ref_id_type'], 'ref_sn' => $pData['ref_sn'], 'act_money' => $pData['act_money']]);
        if(!empty($payment))
        {
            try
            {
                Db::startTrans();
                // 以下状态，不可修改
                if(in_array($payment->getData('pay_status'), [FinancePayment::PAY_STATUS_ALL, FinancePayment::PAY_STATUS_REJECT, FinancePayment::PAY_STATUS_RET_ALL]))
                {
                    $allow = ['invoice_type', 'invoice_title', 'invoice_tax_code' ,'remark'];
                    $pData = Tools::visibleArray($allow, $pData);
                    if(empty($pData))
                    {
                        Db::rollback();
                        return false;
                    }
                }
                $payment->save($pData);
                Hook::listen('finance', $payment);
                Db::commit();
            }catch (DbException $exception)
            {
                Db::rollback();
                Log::info(sprintf("付款单：业务【%s】单号【%s】更新失败，错误信息【%s】", $payment->getData('ref_type'), $payment->ref_sn, $exception->getMessage()));
                return false;
            }
        }
        else
        {
            if(!empty($pData['is_invoice']) && ($defInvoice = FinanceInvoiceSetting::getDefaultInvoice()))
            {
                $pData['invoice_id'] = $defInvoice->invoice_id;
            }
            $payment = FinancePayment::create($pData)->refresh();
        }
        return $payment;
    }

    /**
     * 添加收款单
     * @param array $data 收款信息
     * @return FinanceCash|bool
     * @date 2020/12/27
     * @author longli
     */
    public function addCash($data = [])
    {
        $cData = FinanceCash::getFilterField($data, '');
        if(empty($cData)) return false;
        $cData = Tools::trim($cData);
        $cash = null;
        if(isset($cData['cash_id'])) $cash = FinanceCash::get($cData['cash_id']);
        if(empty($cash) && isset($cData['ref_id_type']) && isset($cData['ref_sn']) && isset($cData['cash_money']))
            $cash = FinanceCash::get(['ref_id_type' => $cData['ref_id_type'], 'ref_sn' => $cData['ref_sn'], 'cash_money' => $cData['cash_money']]);
        if(!empty($cash))
        {
            try
            {
                Db::startTrans();
                $cash->save($cData);
                Hook::listen('finance', $cash);
                Db::commit();
            }catch (DbException $exception)
            {
                Db::rollback();
                Log::info(sprintf("收款单：业务【%s】单号【%s】更新失败，错误信息【%s】", $cash->getData('ref_type'), $cash->ref_sn, $exception->getMessage()));
                return false;
            }
        }
        else
        {
            $cash = FinanceCash::create($cData)->refresh();
        }
        return $cash;
    }

    /**
     * 添加银行
     * @param array $data 银行信息
     * @return FinanceBank|bool
     * @date 2021/01/09
     * @author longli
     */
    public function addBank($data = [])
    {
        $bData = FinanceBank::getFilterField($data, '');
        if(empty($bData)) return false;
        $bData = Tools::trim($bData);
        $bank = null;
        if(isset($bData['bank_id'])) $bank = FinanceBank::get($bData['bank_id']);
        if(empty($bank) && isset($bData['account'])) $bank = FinanceBank::get(['account' => $bData['account']]);
        if(!empty($bank))
        {
            $bank->save($bData);
        }
        else
        {
            $bank = FinanceBank::create($bData)->refresh();
        }
        return $bank;
    }

    /**
     * 添加发票配置信息
     * @param array $data
     * @return FinanceInvoiceSetting|false
     * @date 2021/01/15
     * @author longli
     */
    public function addInvoiceSetting($data = [])
    {
        $iData = FinanceInvoiceSetting::getFilterField($data, '');
        if(empty($iData)) return false;
        $iData = Tools::trim($iData);
        $setting = null;
        if(isset($iData['invoice_id'])) $setting = FinanceInvoiceSetting::get($iData['invoice_id']);
        if(isset($data['bank_id']) && ($bank = FinanceBank::get($data['bank_id'])))
        {
            $iData['bank_address'] = $bank->address;
            $iData['bank_account'] = $bank->account;
        }
        if(!empty($setting))
        {
            $setting->save($iData);
        }
        else
        {
            $setting = FinanceInvoiceSetting::create($iData)->refresh();
        }
        if(!empty($iData['is_default'])) FinanceInvoiceSetting::setDefault($setting, true);
        return $setting;
    }
}